<?php

namespace App\Api\GoModule\Controllers;
use JWTauth;
use DB;
use Log;
use App\Api\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Http\Requests;
use App\Http\Requests\PostRequest;
use Validator;
use App\OrderRecord;
use App\DeliveryRecord;
class UserPostController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
    }
    /**
    *文件名(UserPostController.php)
    *
    *根据乘客当前经纬度返回附近可用车的数量
    *
    *@param $request
    */

    public function carNum(Request $request)
    {
     	$validator = Validator::make($request->all(),[
	'position'=>'required']);
	if($validator)
	{
		//获得乘客经纬度
        	$position = $request->get('position');
         	 //以逗号拆分经纬度，存为一个数组，0为经度，1为纬度
        	$p_data = explode(",", $position);
                //查询司机手机号码，作为查询司机位置的遍历依据
        	$drivers = Redis::sinter('driverPhone');
        	$num = 0;//车辆统计个数num
       		 foreach ($drivers as $driver) {
            		$d_position = Redis::hget('startcar:'.$driver, 'driverPosition');
			if($d_position){
			
            		$d_data = explode(",", $d_position);
			$distance = $this->getDistance($p_data[1],$p_data[0],$d_data[1],$d_data[0]);

               /***满足4.0公里的范围的车辆则算入统计***/
            	if ($distance<=4000)
                $num = $num+1;
           		} 
        	} 
        	$result = $this->returnMsg('200', 'success', ['carNum'=>$num]);
       		return response()->json($result);
        
	}
	else {
		return $this->returnMsg('50001','position is null');;
    	}
   }		

    /**
    *根据乘客端输入的乘客人数、路程距离、车型估价(目前只根据路程，3公里以内5元，以上每0.1公里加0.15元)
    *
    *@param $request
    */

    public function price(Request $request)
    {

	$fromPosition = $request->input('fromPosition');
	$destinationPosition = $request->input('destinationPosition');
	$key = "bb4894e20165ad23730775378768915a";
	$url = "http://restapi.amap.com/v3/distance?origins=$fromPosition&destination=$destinationPosition&type=1&key=$key";

  	$ch = curl_init();
 	curl_setopt($ch, CURLOPT_URL, $url);
 	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  	curl_setopt($ch, CURLOPT_HEADER, 0);
  	$output = curl_exec($ch);
  	curl_close($ch);
  	$data = json_decode($output,true);
  	$distance = 0;
	//如果高得地图API返回的值是空,按照直线距离
	if($data['status']==1){
			$distance = $data['results']['0']['distance'];
	}else{
	    $p_data = explode(",", $fromPosition);
	    $d_data = explode(",", $destinationPosition);
            $distance = $this->getDistance($p_data[1],$p_data[0],$d_data[1],$d_data[0]);//纬度在前，经度在后
	}
	$distance = $distance/1000;
        if ($distance<=3) {
		$p = 5.00;
		return $this->returnMsg('200','success',['price'=>$p,'distance'=>round($distance,1)]);
        } else if($distance<=8){
            $p = 5+2*($distance-3);
            return $this->returnMsg('200','success',['price'=>round($p,2),'distance'=>round($distance,1)]);
		}
		else {
		$p = 5+2.5*($distance-3);
         return $this->returnMsg('200','success',['price'=>round($p,2),'distance'=>round($distance,1)]);
 		 }
       /* $distance = $request->get('distance');
        if ($distance<=3) {
            $result = $this->returnMsg('200', 'success', ['price'=>5]);
            return response()->json($result);
        } else if( $distance<=8 ) {
            $p = 5+1.5*($distance-3);
            $result = $this->returnMsg('200', 'success', ['price'=>$p]);
            return response()->json($result);
        }
		else if( $distance>8 ){
			$p = 5+2*($distance-3);
			return $this->returnMsg('200', 'success',['price'=>$p]);
		}*/
    }

    /**
    *乘客确认用车后，保存订单信息至服务器，用作发布给司机端
    *
    *用车表名称格式
    * @done 验证是否重复提交
    *@param Request $request
    */

    public function orderSave(Request $request)
    {
	
		//get Token	
        $token = JWTAuth::getToken();
        //get the user infomation
        $user_json = JWTAuth::toUser($token);
        //dd($user_json);	
        $user = json_decode($user_json, true);
        //获得用户手机号码
        $userphone = $user['tel'];

   		$checkOrder =  $this->checkBeforeSave($userphone); 
		if($checkOrder){
			return $checkOrder;
		}
		$fromWho = $user['nickname'];
        //存入userphone集合
        $userphone_save = Redis::sadd('userPhone', $userphone);
        //获得出发地名称
        $from = $request->get('from');
        //获得出发地经纬度
        $fromPosition = $request->get('fromPosition');
		$p_data = explode(',',$fromPosition);
 	//获得目的地名称
        $destination = $request->get('destination');
        //获得目的地经纬度
        $destinationPosition = $request->get('destinationPosition');
		
		$price = $this->getPrice($fromPosition,$destinationPosition);
		$price = round($price,2);//四舍五入到两位小数点,精确到分
        //获得乘客人数
        $passengerNum = $request->get('passengerNum');
        //获得车类型
        $motoType = $request->get('motoType');
		$user_invited = DB::table('wechats')->where('tel','=',$userphone)->select('invited')->first();
		$user_invited = $user_invited->invited;
		$orderType = 1;//订单类型1为送人
        $time = date('Y-m-d H:i:s', time());
        $isAccept = 0;
	//获取司机集合
 	//$driverList=[];         
	$driverPhones = Redis::sinter('driverPhone');
	$client = stream_socket_client('tcp://120.77.57.178:8888', $errno, $errmsg, 1); 
          foreach ($driverPhones as $driverPhone) {
	      		$driver = Redis::hgetall('startcar:'.$driverPhone);
            	$d_position = $driver['driverPosition'];
	      		$isFree = $driver['isFree'];
	      		$d_motoType = $driver['motoType'];
				//如果乘客对司机车型车型没要求//取消
				if($motoType==1)
					$motoType = $d_motoType;
              		$d_data = explode(",", $d_position);
   	      			$distance = $this->getDistance($p_data[1],$p_data[0],$d_data[1],$d_data[0]);
   				 /***距离为4公里范围的车辆加入推送名单***/
    			if ($distance<=4000&& $isFree==1)//idFree==1 空闲
        		{
					$data = array( 
					'uid'           => $driverPhone, 
					'userPhone'     => $userphone,   
					'name' 		=>$fromWho,
					'from'          => $from, 
					'fromPosition'  => $fromPosition,
					'destination'   => $destination, 
					'destinationPosition'    => $destinationPosition,
					'passengerNum'  => $passengerNum,
					'motoType'      => $motoType,
					'price'			=> $price,
					'created_at'    => $time,
					'distance'=>($distance/1000),
					'orderType'=>$orderType);
Log::info('test pushorder successful ');
             // 发送数据，注意5678端口是Text协议的端口，Text协议需要在数据末尾加上换行符
		fwrite($client, json_encode($data)."\n");   
                        //  $driverList[]=$driver;
              }
         }
	
        $query = Redis::hmset(
            'usecar:'.$userphone,
	    	'name',$fromWho,
            'from', $from,
            'fromPosition',$fromPosition,
	    	'destination', $destination,
            'destinationPosition', $destinationPosition,
            'passengerNum',$passengerNum,
            'motoType',$motoType,
            'isAccept', $isAccept,
	    	'created_at',$time,
	    	'orderType',$orderType,
			'price',$price,
			'user_invited',$user_invited
        );
	if ($query) {
	     Redis::expire('usecar:'.$userphone,300);
             $result = $this->returnMsg('200', 'save order successfully',['status'=>0]);
             return response()->json($result);
         } else {
             $result = $this->returnMsg('56001', 'fail to save order');
             return response()->json($result);
         }
}
	/*
    *@author guyi 824315402@qq.com
    *@desc 计算价格
    *@param fromPosition 
    *@param destinationPosition
    *@return price
    */
    public function getPrice($fromPosition,$destinationPosition)
 {
		$key = "bb4894e20165ad23730775378768915a";	
		$url = "http://restapi.amap.com/v3/distance?origins=$fromPosition&destination=$destinationPosition&type=1&key=$key";

  		$ch = curl_init();
 		curl_setopt($ch, CURLOPT_URL, $url);
 		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  		curl_setopt($ch, CURLOPT_HEADER, 0);
  		$output = curl_exec($ch);
  		curl_close($ch);
  		$data = json_decode($output,true);
  		$distance = 0;

		if($data['status']==1){
			$distance = $data['results']['0']['distance'];
		}else{
	   	 	$p_data = explode(",", $fromPosition);
	    	$d_data = explode(",", $destinationPosition);
            $distance = $this->getDistance($p_data[1],$p_data[0],$d_data[1],$d_data[0]);
		}
		$distance = $distance/1000;
        if ($distance<=3) {
			return 5;
        } else if($distance<=8){
            $p = 5+2*($distance-3);
            return $p;
		}
		else {
			$p = 5+2.5*($distance-3);
        	return $p;
 		 }
	}
	
	public function checkBeforeSave($userphone)
  {
	/*
	此处验证订单是否重复提交
    */	
	//检测送货订单
		$orders=[];
		$checkDelis = Redis::sinter('send:'.$userphone);
		if($checkDelis)
			foreach($checkDelis as $orderNum){
				$query = Redis::hgetall($orderNum);
				if($query){
				$isAccept = $query['isAccept'];
				switch($isAccept)	{
	  			case 0:
          		return $this->returnMsg('200', 'ok', ['status'=>'00','orderInfo'=>$query]);
  	 			case 1:
 	  		  	$driverPhone = $query['driverPhone'];
	  		  	$driverInfo = $this->getDriverInfo($driverPhone);
                return $this->returnMsg('200', 'ok', ['status'=>'01','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
  	  			case 2:
 	  		  	$driverPhone = $query['driverPhone'];
	  		  	$driverInfo = $this->getDriverInfo($driverPhone);
           		return $this->returnMsg('200', 'ok', ['status'=>'02','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
	  			default:
		 	  	break;
			}
		}
	}

	//检测送人订单
         $checkredis = Redis::exists('usecar:'.$userphone);
         $check_order_mysql3 = OrderRecord::where('userphone','=',$userphone)->where('isAccept','=',3)->first();
         $check_order_mysql4 = OrderRecord::where('userphone','=',$userphone)->where('isAccept','=',4)->first();
         if($checkredis)//若redis有数据则说明有订单正在进行
         {
         $query = Redis::hgetall('usecar:'.$userphone);
		 $isAccept = $query['isAccept'];
		 switch($isAccept)	{
	  		case 0:
          		  return $this->returnMsg('200', 'ok', ['status'=>'0','orderInfo'=>$query]);
  	 		case 1:
 	  		  $driverPhone = $query['driverPhone'];
	  		  $driverInfo = $this->getDriverInfo($driverPhone);
              		  return $this->returnMsg('200', 'ok', ['status'=>'1','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
  	  		case 2:
 	  		  $driverPhone = $query['driverPhone'];
	  		  $driverInfo = $this->getDriverInfo($driverPhone);
              		  return $this->returnMsg('200', 'ok', ['status'=>'2','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
	  		//case 3:
 	  		 // $driverPhone = $query['driverPhone'];
	  		 // $driverInfo = $this->getDriverInfo($driverPhone);
              		  //return $this->returnMsg('200', 'ok', ['status'=>'3','orderInfo'=>$query,'driverInfo'=>$driverInfo]);
			default:
			  break;
			}
         }
        if($check_order_mysql3){//未付款
			$driverPhone = $check_order_mysql3->driverPhone;
	  		$driverInfo = $this->getDriverInfo($driverPhone);
              		return $this->returnMsg('200', 'ok', ['status'=>'3','orderInfo'=>$check_order_mysql3,'driverInfo'=>$driverInfo]);
         	}
		if($check_order_mysql4){//未评论
			$driverPhone = $check_order_mysql4->driverPhone;
	  		$driverInfo = $this->getDriverInfo($driverPhone);
           		return $this->returnMsg('200', 'ok', ['status'=>'4','orderInfo'=>$check_order_mysql4,'driverInfo'=>$driverInfo]);
		}

  }   
}


